<template>
  <div class="policy-management">
    <!-- 搜索和操作区域 -->
    <div class="operation-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="策略名称">
          <el-input
            v-model="queryParams.policyName"
            placeholder="请输入策略名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="疾病编码">
          <el-input
            v-model="queryParams.diseaseCode"
            placeholder="请输入疾病编码"
            clearable
          />
        </el-form-item>
        <el-form-item label="医保类型">
          <el-select
            v-model="queryParams.insuranceType"
            placeholder="请选择医保类型"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option label="居民医保" value="居民医保" />
            <el-option label="职工医保" value="职工医保" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            style="width: 100px"
          >
            <el-option label="启用" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            v-permission="'policy:query'"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="button-group">
        <el-button
          type="primary"
          v-permission="'policy:add'"
          @click="handleAdd"
        >
          <el-icon><Plus /></el-icon>新增策略
        </el-button>
      </div>
    </div>

    <!-- 策略表格 -->
    <el-table
      :data="policyList"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column
        prop="policyId"
        align="center"
        type="index"
        label="序号"
        width="80"
      />
      <el-table-column prop="policyName" label="策略名称" width="150" />
      <el-table-column prop="diseaseCode" label="疾病编码" width="100" />
      <el-table-column prop="insuranceType" label="医保类型" width="110" />
      <el-table-column prop="discount" label="报销比例" width="90">
        <template #default="{ row }">{{ row.discount }}%</template>
      </el-table-column>
      <el-table-column prop="annualLimit" label="年度限额(元)" width="120" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-switch
            v-permission="'policy:edit'"
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button
            v-permission="'policy:edit'"
            size="small"
            @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            v-permission="'policy:delete'"
            size="small"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form
        ref="policyForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="策略名称" prop="policyName">
          <el-input
            v-model="formData.policyName"
            placeholder="请输入策略名称"
          />
        </el-form-item>
        <!-- 医保类型 -->
        <el-form-item label="医保类型" prop="insuranceType">
          <el-select
            v-model="formData.insuranceType"
            placeholder="请选择医保类型"
            clearable
            style="width: 100%"
          >
            <el-option label="居民医保" value="居民医保" />
            <el-option label="职工医保" value="职工医保" />
          </el-select>
        </el-form-item>
        <el-form-item label="疾病编码" prop="diseaseCode">
          <el-input
            v-model="formData.diseaseCode"
            placeholder="请输入疾病编码"
          />
        </el-form-item>
        <el-form-item label="报销比例" prop="discount">
          <el-input-number
            v-model="formData.discount"
            :min="1"
            :max="100"
            :precision="0"
          />
          %
        </el-form-item>
        <el-form-item label="年度限额" prop="annualLimit">
          <el-input-number
            v-model="formData.annualLimit"
            :min="0"
            :precision="2"
          />
          元
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getPolicyList,
  addPolicy,
  updatePolicy,
  deletePolicy,
  changePolicyStatus
} from '@/api/policy'

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  policyName: '',
  diseaseCode: '',
  status: null,
  insuranceType: ''
})

// 表格数据
const policyList = ref([])
const total = ref(0)
const loading = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)

// 表单数据
const formData = reactive({
  policyId: null,
  policyName: '',
  diseaseCode: '',
  discount: 80,
  annualLimit: 5000,
  status: 1,
  insuranceType: ''
})

// 表单验证规则
const rules = reactive({
  policyName: [
    { required: true, message: '请输入策略名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  diseaseCode: [
    { required: true, message: '请输入疾病编码', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  discount: [
    { required: true, message: '请输入报销比例', trigger: 'blur' },
    {
      type: 'number',
      min: 1,
      max: 100,
      message: '范围在 1 到 100',
      trigger: 'blur'
    }
  ],
  annualLimit: [
    { required: true, message: '请输入年度限额', trigger: 'blur' },
    { type: 'number', min: 0, message: '不能小于0', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})

// 获取策略列表
const fetchPolicyList = async () => {
  try {
    loading.value = true
    const res = await getPolicyList(queryParams)
    policyList.value = res.data.data.records
    total.value = res.data.data.total
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.page = 1
  fetchPolicyList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.policyName = ''
  queryParams.diseaseCode = ''
  queryParams.status = ''
  queryParams.insuranceType = ''
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchPolicyList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  queryParams.page = val
  fetchPolicyList()
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    await changePolicyStatus(row.policyId, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    // 如果请求失败，恢复原来的状态
    row.status = row.status === '1' ? '0' : '1'
  }
}

// 新增策略
const handleAdd = () => {
  dialogTitle.value = '新增报销策略'
  isAdd.value = true
  resetForm()
  dialogVisible.value = true
}

// 编辑策略
const handleEdit = (row) => {
  dialogTitle.value = '编辑报销策略'
  isAdd.value = false
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除策略
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该报销策略吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(async () => {
      await deletePolicy(row.policyId)
      ElMessage.success('删除成功')
      fetchPolicyList()
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    policyId: null,
    policyName: '',
    diseaseCode: '',
    discount: 80,
    annualLimit: 5000,
    status: 1,
    insuranceType: ''
  })
}

// 提交表单
const submitForm = async () => {
  try {
    if (isAdd.value) {
      await addPolicy(formData)
      ElMessage.success('新增成功')
    } else {
      await updatePolicy(formData)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    fetchPolicyList()
  } catch (error) {
    console.error(error)
  }
}

// 初始化加载数据
onMounted(() => {
  fetchPolicyList()
})
</script>

<style scoped>
.policy-management {
  padding: 20px;
}

.operation-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.button-group {
  margin-left: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-select {
  width: 100%;
}
</style>
